package com.example.healkep;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.healkep.adapter.DoctorListAdapter;
import com.example.healkep.bean.DietInfoBean;
import com.example.healkep.bean.DietPlanBean;
import com.example.healkep.bean.DoctorListBean;
import com.example.healkep.bean.globalUserInfo;
import com.example.healkep.utils.FastJsonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DietPlanActivity extends AppCompatActivity {

    private TextView text1, text2, text3, text4, text5, text6, text7, text8, text9, text10;
    private Button btn;
    private DietInfoBean dietInfoBean;
    private DietPlanBean dietPlanBean;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diet_plan);

        text1 = findViewById(R.id.text1);
        text2 = findViewById(R.id.text2);
        text3 = findViewById(R.id.text3);
        text4 = findViewById(R.id.text4);
        text5 = findViewById(R.id.text5);
        text6 = findViewById(R.id.text6);
        text7 = findViewById(R.id.text7);
        text8 = findViewById(R.id.text8);
        text9 = findViewById(R.id.text9);
        text10 = findViewById(R.id.text10);
        btn = findViewById(R.id.btn);
        progressBar = findViewById(R.id.progress);
        btn.setOnClickListener((view -> {
            //更换食谱
            getDietPlan();
        }));

        getListData();

    }

    /**
     * 饮食推荐
     */
    private void getDietPlan() {
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            json.put("mainFood", dietInfoBean.getMainFood());
            json.put("vegetables", dietInfoBean.getVegetables());
            json.put("fruit", dietInfoBean.getFruit());
            json.put("meatAndEgg", dietInfoBean.getMeatAndEgg());
            json.put("bean", dietInfoBean.getBean());
            json.put("milk", dietInfoBean.getMilk());
            json.put("nut", dietInfoBean.getNut());
            json.put("oil", dietInfoBean.getOil());
            json.put("salt", dietInfoBean.getSalt());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpClient client = client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));

        final Request request = new Request.Builder()
                .url(LoginActivity.url + "/diet/getRecipe")
                .post(requestBody)
                .build();
        progressBar.setVisibility(View.VISIBLE);
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(DietPlanActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                if(res.length()<5){
                    runOnUiThread(()->{
                        Toast.makeText(DietPlanActivity.this, "暂无数据",Toast.LENGTH_SHORT).show();
                    });
                    return ;
                }
                dietPlanBean = FastJsonUtils.jsonToObject(res, DietPlanBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //Toast.makeText(DietPlanActivity.this, "请求成功" + res, Toast.LENGTH_SHORT).show();
                        String breakFirst = "";
                        String lunch = "";
                        String dinner = "";
                        if (dietInfoBean != null) {
                            if (dietPlanBean.getBreakfirst() != null && dietPlanBean.getBreakfirst().size() != 0) {
                                breakFirst = breakFirst + dietPlanBean.getBreakfirst().get(0).getDetail();
                                lunch = lunch + dietPlanBean.getLunch().get(0).getDetail();
                                dinner = dinner + dietPlanBean.getDinner().get(0).getDetail();
                                for (int i = 1; i < dietPlanBean.getBreakfirst().size(); i++) {
                                    breakFirst = breakFirst + "," + dietPlanBean.getBreakfirst().get(i).getDetail();
                                }

                                for (int i = 1; i < dietPlanBean.getLunch().size(); i++) {
                                    lunch = lunch + "," + dietPlanBean.getLunch().get(i).getDetail();
                                }

                                for (int i = 1; i < dietPlanBean.getDinner().size(); i++) {
                                    dinner = dinner + "," + dietPlanBean.getDinner().get(i).getDetail();
                                }
                            }
                            progressBar.setVisibility(View.GONE);
                            text10.setText("饮食推荐为：\n" + "早餐：" + breakFirst + "\n"
                                    + "午餐：" + lunch + "\n" + "晚餐：" + dinner);
                        }
                    }
                });
            }
        });
    }

    /**
     * 更换食谱
     */
    private void changeDiet() {
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            json.put("mainFood", dietInfoBean.getMainFood());
            json.put("vegetables", dietInfoBean.getVegetables());
            json.put("fruit", dietInfoBean.getFruit());
            json.put("meatAndEgg", dietInfoBean.getMeatAndEgg());
            json.put("bean", dietInfoBean.getBean());
            json.put("milk", dietInfoBean.getMilk());
            json.put("nut", dietInfoBean.getNut());
            json.put("oil", dietInfoBean.getOil());
            json.put("salt", dietInfoBean.getSalt());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpClient client = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));

        final Request request = new Request.Builder()
                .url(LoginActivity.url + "/diet/getRecipe")
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(DietPlanActivity.this, "请求失败", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                if(res.length()<5){
                    runOnUiThread(()->{
                        Toast.makeText(DietPlanActivity.this, "暂无数据",Toast.LENGTH_SHORT).show();
                    });
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DietPlanActivity.this, "请求成功" + res, Toast.LENGTH_SHORT).show();

                    }
                });
            }
        });
    }

    /**
     * 食谱
     */
    private void getListData() {
        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date(System.currentTimeMillis());
            json.put("targetUsername", globalUserInfo.getInstance().getUsername());
            json.put("date", formatter.format(date).toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpClient client = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));

        final Request request = new Request.Builder()
                .url(LoginActivity.url + "/diet/getByPatientAndDate")
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(DietPlanActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String res = response.body().string();
                if(res.length()<5){
                    runOnUiThread(()->{
                        Toast.makeText(DietPlanActivity.this, "暂无数据",Toast.LENGTH_SHORT).show();
                    });
                    return ;
                }
                dietInfoBean = FastJsonUtils.jsonToObject(res, DietInfoBean.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DietPlanActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
                        text1.setText("主食：（单位：份数）：" + dietInfoBean.getMainFood());
                        text2.setText("蔬菜：（单位：份数）：" + dietInfoBean.getVegetables());
                        text3.setText("水果：（单位：份数）：" + dietInfoBean.getFruit());
                        text4.setText("肉蛋：（单位：份数）：" + dietInfoBean.getMeatAndEgg());
                        text5.setText("豆：（单位：份数）：" + dietInfoBean.getBean());
                        text6.setText("奶：（单位：份数）：" + dietInfoBean.getMilk());
                        text7.setText("坚果：（单位：份数）：" + dietInfoBean.getNut());
                        text8.setText("油：（单位：份数）：" + dietInfoBean.getOil());
                        text9.setText("盐：（单位：份数）：" + dietInfoBean.getSalt());
                        getDietPlan();
                    }
                });
            }
        });
    }
}